/**
 * 打印fiber节点
 */
const log = (node) => {
	console.log(node.instance.name)
}

/**
 * fiber节点
 */
function Node(instance) {
	this.instance = instance
	this.return = null
	this.sibling = null
	this.child = null
}
const a1 = { name: 'a1' }
const b1 = { name: 'b1' }
const b2 = { name: 'b2' }
const b3 = { name: 'b3' }

const c1 = { name: 'c1' }
const c2 = { name: 'c2' }

const d1 = { name: 'd1' }
const d2 = { name: 'd2' }

// 模拟 react render function
a1.render = () => [b1,b2,b3]
b1.render = () => null
b2.render = () => [c1]
b3.render = () => [c2]
c1.render = () => [d1,d2]
c2.render = () => null
d1.render = () => null
d2.render = () => null

function link(parent, elements = []) {
	if (elements === null) elements = []
	return elements.reduceRight((target, cur) => {
		const e = new Node(cur)
		e.return = parent
		e.sibling = target
		// return 给下一个节点用 最终回返回左侧节点
		return e
	}, null)
}

let nextUnitWorker = new Node(a1)
beginWork(nextUnitWorker)

function beginWork(nextUnitWorker) {
	let root = nextUnitWorker
	let cur = nextUnitWorker

	while(true) {
		let child = link(cur, cur.instance.render())
		// 有子项
		if (child) {
			cur = child
			continue
		} else {
			log(cur)
		}
		if (cur === root) {
			return
		}

		// 没有子项 如果子项没有值，就向上回溯
		while(cur.sibling === null) {
			log(cur)
			if (cur.return === null || cur.return === root) {
				log(cur.return)
				return
			}
			cur = cur.return
		}

		log(cur)
		// 只有兄弟节点 找兄弟节点
		cur = cur.sibling
	}
}

// TODO: 自定义